from collections import OrderedDict
from datetime import datetime

import pydash
from flask import Blueprint, jsonify, request

from libs import config
from libs.account import Account
from libs.db import DB

taskboard_bp = Blueprint('task_board', __name__)

@taskboard_bp.route('/task_board_summary', methods=['GET'])
def get_tb_summary():
    date = request.args.get('date')
    account_helper = Account()
    if date is None:
        date = datetime.now().strftime("%Y-%m-%d")
    deliver_rows = DB().fetch_all("""
        SELECT user_id, item_name, qty, reward, is_p, item_price, cost, create_time
        FROM deliver WHERE game_date=?
    """, (date,))
    deliver_summary = {}
    for row in deliver_rows:
        user_id = row[0]
        pydash.set_(
            deliver_summary,
            f"{user_id}.total_deliver",
            pydash.get(deliver_summary, f"{user_id}.total_deliver", 0) + 1
        )
        cost = row[6]
        if cost is not None:
            pydash.set_(
                deliver_summary,
                f"{user_id}.total_cost",
                pydash.get(deliver_summary, f"{user_id}.total_cost", 0) + row[6]
            )
        is_p = row[4]
        if is_p == 1:
            pydash.set_(
                deliver_summary,
                f"{user_id}.total_p",
                pydash.get(deliver_summary, f"{user_id}.total_p", 0) + row[3]
            )

        total_p = pydash.get(deliver_summary, f"{user_id}.total_p", 0)
        if total_p > 0:
            pydash.set_(
                deliver_summary,
                f"{user_id}.p_price",
                int(pydash.get(deliver_summary, f"{user_id}.total_cost", 0) / total_p)
            )

        create_time = row[7]
        min_time = pydash.get(deliver_summary, f"{user_id}.min_time")
        max_time = pydash.get(deliver_summary, f"{user_id}.max_time")
        if min_time is None or create_time < min_time:
            pydash.set_(deliver_summary, f"{user_id}.min_time", create_time)
        if max_time is None or create_time > max_time:
            pydash.set_(deliver_summary, f"{user_id}.max_time", create_time)
    result = {}
    for user_id in deliver_summary:
        account = account_helper.get(user_id)
        summary = {
            "user_id": user_id,
            "is_vip": account.get('is_vip'),
            "name": account.get('user_name'),
            "game_date": date,
        }
        summary.update(pydash.get(deliver_summary, f"{user_id}", {}))
        result[user_id] = summary

    return jsonify({"code": 0, "result": result})

@taskboard_bp.route('/deliver_summary', methods=['GET'])
def get_deliver_summary():
    date = request.args.get('date')
    if date is None:
        date = datetime.now().strftime("%Y-%m-%d")
    user_id = request.args.get('user_id')

    sql = """
           SELECT user_id, item_name, qty, reward, is_p, item_price, cost, create_time
           FROM deliver WHERE game_date=?
       """
    if user_id is not None:
        sql += " and user_id = " + user_id
    sql += " ORDER BY ID ASC "
    items = config.get_items()

    deliver_rows = DB().fetch_all(sql, (date, ))
    deliver_summary = {}
    deliver_list = []
    for row in deliver_rows:
        user_id = row[0]
        item_name = row[1]
        item_class = items.get(item_name, {}).get('class', 'unknown')
        total_key = f"total_deliver"
        pydash.set_(
            deliver_summary,
            total_key,
            pydash.get(deliver_summary, total_key, 0) + 1
        )
        per_class_total_key = f"per_class.{item_class}.total_deliver"
        pydash.set_(
            deliver_summary,
            per_class_total_key,
            pydash.get(deliver_summary, per_class_total_key, 0) + 1
        )
        per_item_total_key = f"per_item.{item_name}.total_deliver"
        pydash.set_(
            deliver_summary,
            per_item_total_key,
            pydash.get(deliver_summary, per_item_total_key, 0) + 1
        )
        cost = row[6]
        if cost is not None:
            pydash.set_(
                deliver_summary,
                f"total_cost",
                pydash.get(deliver_summary, f"total_cost", 0) + cost
            )

            per_class_cost_key = f"per_class.{item_class}.total_cost"
            pydash.set_(
                deliver_summary,
                per_class_cost_key,
                pydash.get(deliver_summary, per_class_cost_key, 0) + cost
            )

        is_p = row[4]
        reward = row[3]
        if is_p == 1:
            p_key = f"total_p"
            pydash.set_(
                deliver_summary,
                p_key,
                pydash.get(deliver_summary, p_key, 0) + reward
            )
            per_class_p_key = f"per_class.{item_class}.total_p"
            pydash.set_(
                deliver_summary,
                per_class_p_key,
                pydash.get(deliver_summary, per_class_p_key, 0) + reward
            )

        total_p = pydash.get(deliver_summary, f".total_p", 0)
        if total_p > 0:
            pydash.set_(
                deliver_summary,
                f"p_price",
                int(pydash.get(deliver_summary, f"total_cost", 0) / total_p)
            )

    per_item = deliver_summary.get('per_item', {})
    per_item_sorted = pydash.sort_by(per_item.items(), lambda item: item[1]['total_deliver'], reverse=True)
    deliver_summary['per_item'] = dict(per_item_sorted)
    per_class = deliver_summary.get('per_class', {})
    per_class_sorted = pydash.sort_by(per_class.items(), lambda item: item[1]['total_deliver'], reverse=True)
    deliver_summary['per_class'] = dict(per_class_sorted)

    return jsonify({"code": 0, "summary": deliver_summary, "list": deliver_list})

@taskboard_bp.route('/taskboards', methods=['GET'])
def get_taskboard_list():
    date = request.args.get('date')
    if date is None:
        date = datetime.now().strftime("%Y-%m-%d")
    sql = """
           SELECT user_id, game_date, create_time, position, item_name, qty, reward, is_p, item_price, cost  
           FROM task_board WHERE game_date=?
           ORDER BY user_id asc, position asc
       """
    items = config.get_items()

    taskboard_rows = DB().fetch_all(sql, (date,))
    taskboard_list = []
    for row in taskboard_rows:
        item_name = row[4]
        item = items.get(item_name, {})
        item_class = item.get('class', 'unknown')
        item_tier = item.get('tier', 0)
        taskboard_list.append({
            "user_id": row[0],
            "game_date": row[1],
            "create_time": row[2],
            "position": row[3],
            "item_name": item_name,
            "item_class": item_class,
            "item_tier": item_tier,
            "qty": row[5],
            "reward": row[6],
            "is_p": row[7],
            "item_price": row[8],
            "cost": row[9]
        })
    return jsonify({"code": 0, "list": taskboard_list})
@taskboard_bp.route('/deliver_list', methods=['GET'])
def get_deliver_list():
    date = request.args.get('date')
    if date is None:
        date = datetime.now().strftime("%Y-%m-%d")
    user_id = request.args.get('user_id')

    sql = """
       SELECT user_id, item_name, qty, reward, is_p, item_price, cost, create_time, position
       FROM deliver WHERE game_date=?
   """
    if user_id is not None:
        sql += " and user_id = " + user_id
    sql += " ORDER BY ID DESC "
    items = config.get_items()

    deliver_rows = DB().fetch_all(sql, (date,))
    deliver_list = []
    per_class = {}
    for row in deliver_rows:
        item_name = row[1]
        qty = row[2]
        reward = row[3]
        cost = row[6]
        is_p = row[4]
        item = items.get(item_name, {})
        item_class = item.get('class', 'unknown')
        item_tier = item.get('tier', 0)
        pydash.set_(per_class, f"{item_class}.count", pydash.get(per_class, f"{item_class}.count", 0) + 1)
        pydash.set_(per_class, f"{item_class}.qty", pydash.get(per_class, f"{item_class}.qty", 0) + qty)
        if cost is not None:
            pydash.set_(per_class, f"{item_class}.cost", pydash.get(per_class, f"{item_class}.cost", 0) + cost)
        if is_p:
            pydash.set_(per_class, f"{item_class}.p_count", pydash.get(per_class, f"{item_class}.p_count", 0) + reward)
        deliver_list.append({
            "item_name": item_name,
            "item_class": item_class,
            "item_tier": item_tier,
            "qty": qty,
            "price": row[5],
            "is_p": is_p,
            "item_price": row[5],
            "reward": reward,
            "cost": cost,
            "create_time": row[7],
            "position": row[8],
        })
    return jsonify({"code": 0, "list": deliver_list, "per_class": per_class})